import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import findIndex from  'lodash/findIndex'
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import AddOrEditStaffs from './addOrEditUser';
import Detail from './Detail';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ profit_report, loading, global }) => ({
  profit_report,
  global,
  loading: loading.models.profit_report,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      profit_report: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        profit_report: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'profit_report/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'profit_report/changeLoaded',
          });
          dispatch({
            type: 'profit_report/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'profit_report/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'profit_report/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'profit_report/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      profit_report: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>
          {
            find(this.permissions, { name: 'profit_report_operation' }) &&
            <Button
              icon="plus"
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              添加利润表
            </Button>
          }
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    let data=[]
    for(let key in formValues){
      if(key.indexOf('$')>0&&key.indexOf('限值')<0){
        let address=key.split('$')[0];
        const exit =findIndex(data,function(o) {
          return o.address===address
        })
        if(exit>=0){
          data[exit][key.split('$')[1]]=formValues[key]
        }else{
          data.push({
            address:address,
            [key.split('$')[1]]:formValues[key]
          })
        }
      }
    }
    let items=[]
    for(let i=0;i<data.length;i++){
      let item=[]
      for(let key in data[i]){
        item.push({
          key:key,
          value:data[i][key],
        })
      }
      items.push({
        name:data[i].address,
        item:item
      })

    }
    console.log('items',items)
    let formData = new FormData();
    if(formValues.file){
      formData.append("original_file", formValues.file.file);
    }
    formData.append("customize[month]", moment(formValues.month).format('YYYY-MM'));
    formData.append("company_id", sessionStorage.getItem('company_id'));
    formData.append("customize[director]",formValues.director);
    formData.append("customize[author]", formValues.author);
    formData.append("template", 1);

    items.forEach((item, i)=> {
      formData.append(`items[${i}][name]`, item.name);
      item.item.forEach((item2, i2)=> {
        formData.append(`items[${i}][items][${i2}][key]`, item2.key);
        formData.append(`items[${i}][items][${i2}][value]`, item2.value);
      })
    })
    const that = this;
    this.props.dispatch({
      type: 'profit_report/add',
      payload:formData,
      callback() {
        message.success('添加利润表成功');
        that.setState({
          addModal: false,
        });
        const {
          profit_report: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      name: '',
      page: 1,
      year:moment().format('YYYY'),
      per_page: 30,
    });
  };
  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    let data=[]
    for(let key in formValues){
      if(key.indexOf('$')>0&&key.indexOf('限值')<0){
        let address=key.split('$')[0];
        const exit =findIndex(data,function(o) {
          return o.address===address
        })
        if(exit>=0){
          data[exit][key.split('$')[1]]=formValues[key]
        }else{
          data.push({
            address:address,
            [key.split('$')[1]]:formValues[key]
          })
        }
      }
    }
    let items=[]
    for(let i=0;i<data.length;i++){
      let item=[]
      for(let key in data[i]){
        item.push({
          key:key,
          value:data[i][key],
        })
      }
      items.push({
        name:data[i].address,
        item:item
      })

    }
    console.log('items',items)
    let formData = new FormData();
    if(formValues.file){
      // formData.append("original_file_delete", 1);
      formData.append("original_file", formValues.file.file);
    }
    formData.append("customize[month]", moment(formValues.month).format('YYYY-MM'));
    formData.append("customize[director]",formValues.director);
    formData.append("customize[author]", formValues.author);
    formData.append("company_id", sessionStorage.getItem('company_id'));
    formData.append("template", 1);
    items.forEach((item, i)=> {
      formData.append(`items[${i}][name]`, item.name);
      item.item.forEach((item2, i2)=> {
        formData.append(`items[${i}][items][${i2}][key]`, item2.key);
        formData.append(`items[${i}][items][${i2}][value]`, item2.value);
      })
    })
    formData.append("type", 2);
    const that = this;
    this.props.dispatch({
      type: 'profit_report/edit',
      payload:{
        id:this.state.editRecord.id,
        formData
      },
      callback() {
        message.success('修改利润表成功');
        that.setState({
          editModal: false,
        });
        const {
          profit_report: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `profit_report/remove`,
      payload: { id },
      callback: () => {
        message.success('删除利润表成功');
        const {
          profit_report: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  render() {
    const that = this;
    const {
      profit_report: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            profit_report: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '月份',
        width: 150,
        key: 'month',
        formatter: (event) => {
          return `${event.row.customize.month}`;
        },
      },
      {
        name: '部门负责人',
        width: 150,
        key: 'director',
        formatter: (event) => {
          return `${event.row.customize.director}`;
        },
      },
      {
        name: '制表',
        width: 150,
        key: 'author',
        formatter: (event) => {
          return `${event.row.customize.author}`;
        },
      },
      {
        name: '创建时间',
        width: 150,
        key: 'created_at',
      },
      {
        name: '创建人',
        width: 150,
        key: 'user',
        formatter: (event) => {
          return `${event.row.user.name}`;
        },
      },
      {
        name: '操作',
        width: 180,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            type="primary"
            size="small"
            icon="eye"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
          {
            find(this.permissions, { name: 'profit_report_operation' }) &&
            <Fragment>

              <Button
                type="primary"
                size="small"
                icon="edit"
                onClick={(e) => {
                  this.setState({
                    editRecord:event.row,
                    editModal:true
                  })
                }
                }
              >修改
              </Button>
              <Button
                type="danger"
                size="small"
                icon="delete"
                onClick={(e) => {
                  confirm({
                    title: `确定要删除"${event.row.customize.month}"利润表吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered: true,
                    maskClosable: true,
                    onOk() {
                      that.handleDelete(event.row.id);
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }
                }
              >删除
              </Button>
            </Fragment>
          }

        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>利润表</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            onGridRowsUpdated={this.onGridRowsUpdated}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'profit_report/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加利润表"/>}
        className="addModal"
        visible={this.state.addModal}
        centered
        width={800}
        onCancel={() => {
          this.setState({ addModal: false });
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.infoModal} modalClass="infoModal"
                                title={`${this.state.editRecord.customize&&this.state.editRecord.customize.month}利润表详情`}/>}
        destroyOnClose
        visible={this.state.infoModal}
        centered
        onOk={this.handleEdit}
        className="infoModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={750}
        onCancel={() => {
          this.setState({ infoModal: false, editRecord: {} });
        }}
        footer={null}
      >
        <Detail
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.InfoForm = inst}
        />

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改${this.state.editRecord.customize&&this.state.editRecord.customize.month}利润表`}/>}
        className="editModal"
        destroyOnClose
        visible={this.state.editModal}
        centered
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={800}
        onCancel={() => {
          this.setState({ editModal: false });
        }}
        onOk={this.handleEdit}
      >
        <AddOrEditUser
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}/>

      </Modal>
    </div>;
  }
}

export default BasicList;
